package com.lswms.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.lswms.common.exception.ErrorCode;
import com.lswms.common.exception.RenException;
import com.lswms.common.redis.RedisUtils;
import com.lswms.common.service.impl.CrudServiceImpl;
import com.lswms.common.utils.HttpClientUtils;
import com.lswms.common.utils.IpUtils;
import com.lswms.common.utils.ZqDateUtil;
import com.lswms.dao.YnDcLoginDao;
import com.lswms.dto.YnDcLoginDTO;
import com.lswms.dto.YnDcUserBlackDTO;
import com.lswms.dto.YnPayRecordDTO;
import com.lswms.dto.YnUserDTO;
import com.lswms.dto.vo.req.DcIndexDataReq;
import com.lswms.dto.vo.req.DcLoginReq;
import com.lswms.dto.vo.req.DcQueryCreditReq;
import com.lswms.dto.vo.req.DcQueryReportReq;
import com.lswms.dto.vo.req.DcQueryStatusReq;
import com.lswms.dto.vo.resp.DcDataInfoResp;
import com.lswms.dto.vo.resp.DcIndexDataResp;
import com.lswms.dto.vo.resp.DcQueryCreditResp;
import com.lswms.dto.vo.resp.DcQueryReportResp;
import com.lswms.dto.vo.resp.GetAiResultResp;
import com.lswms.dto.vo.resp.LoginResp;
import com.lswms.entity.YnDcLoginEntity;
import com.lswms.entity.YnDcProdEntity;
import com.lswms.entity.YnLotteryTicketOrderEntity;
import com.lswms.entity.YnPayRecordEntity;
import com.lswms.entity.YnUserEntity;
import com.lswms.redis.SysParamsRedis;
import com.lswms.service.SysConfigService;
import com.lswms.service.YnDcLoginService;
import com.lswms.service.YnDcProdService;
import com.lswms.service.YnDcUserBlackService;
import com.lswms.service.YnPayRecordService;
import com.lswms.service.YnUserService;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;

import javax.servlet.http.HttpServletRequest;

import lombok.extern.slf4j.Slf4j;

/**
 * 用户登录信息
 *
 * @author Mark sunlightcs@gmail.com
 * @since 1.0.0 2020-07-24
 */
@Service
@Slf4j
public class YnDcLoginServiceImpl extends CrudServiceImpl<YnDcLoginDao, YnDcLoginEntity, YnDcLoginDTO> implements YnDcLoginService {

    @Autowired
    private SysParamsRedis sysParamsRedis;
    
    @Autowired
    private RedisUtils redisUtils;

	@Autowired
	private YnPayRecordService ynPayRecordService;
	
	@Autowired
	private YnUserService ynUserService;

	@Autowired
	private SysConfigService sysConfigService;
	
	@Autowired
	private YnDcUserBlackService ynDcUserBlackService;
	
	@Autowired
	private YnDcProdService ynDcProdService;

    
    @Override
    public QueryWrapper<YnDcLoginEntity> getWrapper(Map<String, Object> params){
        String id = (String)params.get("id");
        String username = (String)params.get("username");

        QueryWrapper<YnDcLoginEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(id), "id", id);
        wrapper.eq(StringUtils.isNotBlank(username), "username", username);

        return wrapper;
    }

    /**
     * 登录
     */
	@Override
	public LoginResp login(DcLoginReq req,HttpServletRequest request) {
		log.info("登录，参数:{}",JSON.toJSONString(req));
		String mobile = req.getMobile();
		//判断用户是否注册
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("mobile", mobile);
		List<YnUserDTO> ynuserList = ynUserService.list(params);
		//用户id
		String userId = "";
		if(ynuserList != null && ynuserList.size() > 0){
			YnUserDTO ynuser = ynuserList.get(0);
			//修改登录信息
			YnUserEntity user = new YnUserEntity();
			user.setIp(IpUtils.getIpAddr(request));
			user.setLasttime(ZqDateUtil.yyyyMMddHHmmss(ZqDateUtil.getNow()));
			user.setId(ynuser.getId());
			user.setUpdateDate(ZqDateUtil.getNow());
			ynUserService.updateById(user);
			userId = ynuser.getId()+"";
		}else{
			YnUserEntity user = new YnUserEntity();
			user.setIp(IpUtils.getIpAddr(request));
			user.setMobile(mobile);
			user.setLasttime(ZqDateUtil.yyyyMMddHHmmss(ZqDateUtil.getNow()));
			user.setBalance(BigDecimal.ZERO);
			user.setChallenge(0);
			user.setStatus(1);
			user.setResource(2);
			user.setCreateDate(ZqDateUtil.getNow());
			ynUserService.insert(user);
			userId = user.getId()+"";
		}
		//token 
		String token = UUID.randomUUID().toString().replaceAll("-", "");
		//保存用户id和token
		sysParamsRedis.set("userinfo:"+userId, token);
		
		LoginResp resp = new LoginResp();
		resp.setToken(token);
		resp.setUserId(userId+"");
		return resp;

	}

	/**
	 * 信用信息
	 */
	@Override
	public DcQueryCreditResp queryCreditInfo(YnUserEntity ynuser) {
		log.info("信用信息，参数:{}",JSON.toJSONString(ynuser));
		DcQueryCreditResp resp = new DcQueryCreditResp();
		//redisUtils.set(key, value, expire);
		Object value = redisUtils.get("CreditInfo:"+ynuser.getId());
		if(value != null){
			resp.setStatus("1");
		}
		//累计升级用户
		Object obj = redisUtils.get("TotalUp");
		String totalCount = (String)obj;
		//综合额度提升
		int amountUp = ThreadLocalRandom.current().nextInt(150, 200);
		//贷款通过率
		int successRate = ThreadLocalRandom.current().nextInt(90, 99);
		//综合被拒概率
		int refuseRate = ThreadLocalRandom.current().nextInt(80, 100);
		
		resp.setAmountUp("+"+amountUp+"%");
		resp.setTotalCount(totalCount);
		resp.setSuccessRate(successRate+"%");
		resp.setRefuseRate(refuseRate+"%");
		log.info("信用信息，返回:{}",JSON.toJSONString(resp));
		return resp;
	}

	/**
	 * 信用信息支付状态
	 */
	@Override
	public String queryPayStatus(DcQueryStatusReq dto) {
		log.info("开始信用信息支付状态参数:dto:{}",JSON.toJSONString(dto));
		String tradNo = dto.getUuid();
		if(StringUtils.isBlank(tradNo)){
			throw new RenException(ErrorCode.TRAD_ERROR);
		}
		//查询交易是否存在
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("uuid", tradNo);
		params.put("status", 0);
		List<YnPayRecordDTO> recordList = ynPayRecordService.list(params);
		log.info("充值回调参数:record:{}",JSON.toJSONString(recordList));
		if(recordList == null){
			throw new RenException(ErrorCode.TRAD_ERROR);
		}
		YnPayRecordDTO record = recordList.get(0);
		//充值+余额
        JSONObject retJson = HttpClientUtils.httpGet("http://149.129.235.68:29918/pay/api/in/getPayStatus?appKey=54fff46929fb49de8ed298e2026ec444&transactionId="+tradNo);
        log.info("查询支付状态结果：{}",JSON.toJSONString(retJson));
        
        if(retJson != null && retJson.getIntValue("code") == 200 
        		&& "SUCCESS".equals(retJson.getString("message"))) {
        	
        	JSONObject retJson1 = (JSONObject)retJson.get("result");
        	if(retJson1 != null){
            	String uuid = retJson1.getString("transactionId");
            	String payStatus = retJson1.getString("payStatus");
            	int payMoney = retJson1.getIntValue("payMoney");
            	if("SUCCESS".equals(payStatus) && uuid.equals(tradNo) 
            			&& record.getAmt().compareTo(new BigDecimal(payMoney)) == 0){
            		return "success";
            	}
        	}
        }
		log.info("结束充值回调操作。。。。。。。");
		return "fail";
	}

	/**
	 * 获取报告
	 */
	@Override
	public DcQueryReportResp queryReport(DcQueryReportReq dto,YnUserEntity ynuser) {
		//740~799，信用等级：AAA 780~799；AA 760~780; A 740~760
		Object obj = redisUtils.get("CreditInfo-msg:"+ynuser.getId());
		if(obj != null){
			DcQueryReportResp resp = JSON.parseObject((String)obj, DcQueryReportResp.class);
			return resp;
		}
		int random = ThreadLocalRandom.current().nextInt(740, 799);
		String pointA = "";
		if(random >= 740 && random < 760){
			pointA = "A";
		}else if(random >= 760 && random < 780){
			pointA = "AA";
		}else if(random >= 780 && random <= 799){
			pointA = "AAA";
		}
		DcQueryReportResp resp = new DcQueryReportResp();
		resp.setCardNo(dto.getCardNo());
		resp.setMobile(dto.getMobile());
		resp.setName(dto.getName());
		resp.setReportA(pointA);
		resp.setReportEx("30:00");
		resp.setReportPoint(random+"");
		resp.setReportTime(ZqDateUtil.yyyyMMddHHmmss(ZqDateUtil.getNow()));
		
		redisUtils.set("CreditInfo:"+ynuser.getId(), "1", 1800);
		redisUtils.set("CreditInfo-msg:"+ynuser.getId(), JSON.toJSONString(resp),1800);
		
		return resp;
	}

	/**
	 * 智能推荐获取结果
	 */
	@Override
	public GetAiResultResp getAiResult(YnUserEntity ynuser) {
		//累计推荐
    	String ymd = ZqDateUtil.yyyyMMdd(ZqDateUtil.getNow());
    	Object obj1 = redisUtils.hGet("TotalRecommend:",ymd);

    	String value = sysConfigService.queryConfig("PlamtProd");
    	
    	GetAiResultResp resp = new GetAiResultResp();
    	resp.setPlamtProd(value.split("_")[0]);
    	resp.setQuickLoan(value.split("_")[1]);
    	resp.setRecommendCount((String)obj1);
    	
    	List<DcDataInfoResp> listInfo = new ArrayList<DcDataInfoResp>();
    	//查询当前用户是否在黑名单
    	Map<String, Object> params = new HashMap<String, Object>();
    	params.put("username", ynuser.getMobile());
    	List<YnDcUserBlackDTO> list = ynDcUserBlackService.list(params);
    	if(list == null){
    		YnDcProdEntity entity = ynDcProdService.getRecommendProd();
    		DcDataInfoResp info = ynDcProdService.convetInfo(entity);
    		listInfo.add(info);
    	}
    	resp.setList(listInfo);
    	
		return resp;
	}


}
